#!/bin/bash
#build-latex script v. 1.05 (NO OPEN IN MAC OS X)
#To use the build LaTeX script, under Linux, type in the following into Texmakers settings under "PdfLaTeX":
#/home/USER/Scripts/build-latex-cross.sh '%.tex'
#Replace USER with your user name

#To use the build LaTeX script, under Mac OS X, type in the following into Texmakers settings under "PdfLaTeX":
#"/Users/USER/Scripts/build-latex-cross.sh" '%.tex'
#Replace USER with your user name
#"/usr/texbin/pdflatex" -synctex=1 -interaction=nonstopmode %.tex

dist=""

tmp=$(uname -a | grep Darwin)
if [[ "$tmp" != "" ]]; then
	dist="mac"
fi

tmp=$(uname -a | grep Linux)
if [[ "$tmp" != "" ]]; then
	dist="linux"
fi

if [[ "$1" == "--nobib" ]]; then
	x=$2
	nobib=1
else
	x=$1
	nobib=0
fi

directory=${x%/*}
directory=$(echo $directory | cut -c 2-)
if [[ -d $directory ]]; then
	cd $directory
fi

error=0
x=$(echo "$x" | cut -c 2- | rev | cut -c 2- | rev)
z=$(echo "$x" | rev | sed 's/xet.//' | rev)
for i in {1..3}; do
	if [[ $error == 0 ]]; then
		if [[ "$dist" == "linux" ]]; then
			#pdflatex -interaction=nonstopmode %.tex
			pdflatex -interaction=nonstopmode -shell-escape	-synctex=1 "$x"
			error=$?
		elif [[ "$dist" == "mac" ]]; then
			#"/usr/texbin/pdflatex" -interaction=nonstopmode %.tex
			"/usr/texbin/pdflatex" -interaction=nonstopmode -shell-escape -synctex=1 "$x"
			error=$?
		else
			echo "OS not supported!"
		fi
		if [[ $i == 1 ]]; then
			if [[ $nobib == 0 ]]; then
				bibtex "$z"
				error=$?
			fi
		fi
	fi
done

for i in ".aux" ".lox" ".out" ".toc" ".nav" ".snm" ".bbl" ".blg" ".lof" ".lot" ".run.xml" "-blx.bib" ; do
	y="$z$i"
	if [ -f "$y" ]; then
		rm "$y"
	fi
done

if [[ $error == 0 ]]; then
	y="$z.log"
	rm "$y"
	if [[ "$dist" == "linux" ]]; then
		evince "$z.pdf" &
	elif [[ "$dist" == "mac" ]]; then
		#open "$z.pdf" &
		echo .
	fi
fi

exit $error
